﻿using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Web;
using MuzoBlog.Core.BussinessLogic.Settings;
using System.Web.Security;
using System;
using MuzoBlog.Core.Helpers;

namespace MuzoBlog.Core.BussinessLogic.Languages
{
    public abstract class UserManager
    {
        // TODO: GetUser
        // TODO: GetUserID
        // TODO: Login: Use session 

        public static bool Login(string username, string password)
        {
            string plainPassword = EncryptionHelper.Decrypt(SettingManager.GetStringValue("EncryptionKey"), MuzoApp.Db.Info.Password);

            if (MuzoApp.Db.Info.Username != username || plainPassword != password)
                return false;

            var loginGuid = Guid.NewGuid().ToString();
            var ticket = new FormsAuthenticationTicket(
                1,
                loginGuid,
                DateTime.Now, // Name
                DateTime.Now.AddDays(1),
                false,
                loginGuid, // UserData
                FormsAuthentication.FormsCookiePath
            );

            string encTicket = FormsAuthentication.Encrypt(ticket);
            FormsAuthentication.SetAuthCookie(username, true);

            var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            httpCookie.Expires = DateTime.Now.AddMinutes(90);

            HttpContext.Current.Request.Cookies.Add(httpCookie);

            if (HttpContext.Current.Request.QueryString["ReturnUrl"] != null)
                HttpContext.Current.Response.Redirect(HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString["ReturnUrl"]));
            else
                HttpContext.Current.Response.Redirect(FormsAuthentication.DefaultUrl);

            return false;
        }
    }
}
